package week05.necessary.jdbc.base;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 抽象Jdbc示例
 */
@Slf4j
public abstract class AbstractJdbcExampleImpl implements IJdbcExample {
    protected static final String MYSQL_URL = "jdbc:mysql://localhost:3306/week05";
    protected static final String MYSQL_USER = "root";
    protected static final String MYSQL_PASSWORD = "root";

    @Override
    public Connection getConnection() throws SQLException {
        log.info("[获取数据库连接]url={},user={},pass={}", MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);
        return DriverManager.getConnection(MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);
    }

    @Override
    public void insertExample(String sql, Object... params) throws SQLException {
        int effectRows = getConnection().createStatement().executeUpdate(sql);
        log.info("[新增操作]sql={},effect-rows={}", sql, effectRows);
    }

    @Override
    public void updateExample(String sql, Object... params) throws SQLException {
        int effectRows = getConnection().createStatement().executeUpdate(sql);
        log.info("[修改操作]sql={},effect-rows={}", sql, effectRows);
    }

    @Override
    public void deleteExample(String sql, Object... params) throws SQLException {
        int effectRows = getConnection().createStatement().executeUpdate(sql);
        log.info("[删除操作]sql={},effect-rows={}", sql, effectRows);
    }

    @Override
    public void queryExample(String sql, Object... params) throws SQLException {
        ResultSet resultSet = getConnection().createStatement().executeQuery(sql);
        log.info("[查询操作]sql={}", sql);
        while (resultSet.next()) {
            log.info("[查询操作-返回数据]{}", resultSet.getObject(1));
        }
    }
}
